package com.taotao.doctor.service.impl;

import com.taotao.common.core.domain.Result;
import com.taotao.common.security.utils.SecurityUtils;
import com.taotao.doctor.domain.po.MedDoctorReview;
import com.taotao.doctor.domain.vo.MedDoctorReviewVo;
import com.taotao.doctor.mapper.MedDoctorReviewMapper;
import com.taotao.doctor.service.MedDoctorReviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class MedDoctorReviewServiceImpl implements MedDoctorReviewService {
    @Autowired
    private MedDoctorReviewMapper medDoctorReviewMapper;

    @Override
    public Result list() {
        //实现查询医生的医生评价列表
        Long doctorId = SecurityUtils.getUserId();
        List<MedDoctorReviewVo> reviewList = medDoctorReviewMapper.list(doctorId);

        //创建一个map,用于快速查找每个评论的父评论
        HashMap<Long, MedDoctorReviewVo> reviewMap = new HashMap<>();
        for (MedDoctorReviewVo reviewVo : reviewList) {
            reviewMap.put(reviewVo.getReviewId(), reviewVo);
        }

        //分离出根评论和子评论
        List<MedDoctorReviewVo> reviewVos = new ArrayList<>();
        //遍历所有评论,找到每个评论的父评论,并构建树形结构
        for (MedDoctorReviewVo reviewVo : reviewList) {
            if (reviewVo.getParentReviewId() == null) {
                //父级评论为空,说明是根评论,直接添加
                reviewVos.add(reviewVo);
            }
            //查找父级评论
            MedDoctorReviewVo parentReviewVo = reviewMap.get(reviewVo.getParentReviewId());
            if (parentReviewVo != null) {
                //父级评论不为空,说明不是根评论,需要找到父评论并添加到树形结构中
                parentReviewVo.getChildren().add(reviewVo);
            }
        }
        return Result.success(reviewVos);

    }

    @Override
    public Result replyReview(Long reviewId, String reviewText) {
        //根据id回显评论内容
        MedDoctorReview review = medDoctorReviewMapper.selectByPrimaryKey(reviewId);

        //插入回复评论
        MedDoctorReview doctorReview = new MedDoctorReview();
        doctorReview.setPatientId(review.getPatientId());
        doctorReview.setMedDoctorId(review.getMedDoctorId());
        doctorReview.setReviewText(reviewText);
        doctorReview.setParentReviewId(reviewId);
        medDoctorReviewMapper.insert(doctorReview);
        return Result.success();


    }
}
